﻿@using System.Diagnostics.CodeAnalysis

@inherits InputBase<bool?>

<CascadingValue Value="this">
    <label class="form-check-label">@Text</label>
    <div class="form-check form-switch">
        <input type="checkbox" checked="@CurrentValue"
               class="@CssClass"
               @attributes="AdditionalAttributes"
               disabled="@IsDisabled()"
               onchange="@((ChangeEventArgs e) => ChangeValue(e))" />
        @ChildContent
    </div>
</CascadingValue>

@code {
    [Parameter]
    public RenderFragment? ChildContent { get; set; }

    /// <summary>
    /// Switch text.
    /// </summary>
    [Parameter]
    public string? Text { get; set; }

    /// <summary>
    /// Is switch disabled
    /// </summary>
    [Parameter]
    public bool Disabled { get; set; }

    protected override bool TryParseValueFromString(string? value,
        [MaybeNullWhen(false)] out bool? result,
        [NotNullWhen(false)] out string validationErrorMessage)
    {
        validationErrorMessage = "";
        if (value != null)
        {
            result = bool.Parse(value);
        }
        else
        {
            result = false;
        }
        return true;
    }

    /// <inheritdoc/>
    public new string CssClass
    {
        get;
        set;
    } = "form-check-input";

    private string? IsDisabled()
    {
        return Disabled ? "disabled" : null;
    }

    private void ChangeValue(ChangeEventArgs e)
    {
        bool value = Convert.ToBoolean(e.Value);
        CurrentValue = value;
        OnChange?.Invoke(value);
    }

    /// <summary>
    /// Receive notification when user changes the value.
    /// </summary>
    [Parameter]
    public Action<bool>? OnChange { get; set; }
}